package com.keliangliu.demo.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.concurrent.TimeUnit;

public class NettyClient {

    private Boolean reconnectFlag = false;


    public void connect(){
        // 线程池(事件处理线程池)
        NioEventLoopGroup group = new NioEventLoopGroup();
        // 辅助启动类
        Bootstrap b = new Bootstrap();
        try {
                   b.group(group) // 把线程池放进来
                    .channel(NioSocketChannel.class)
                    .handler(new ClientChannelInitializer())
                    .connect("localhost",9999)
                    .addListener((ChannelFutureListener) channelFuture -> {
                final EventLoop eventLoop = channelFuture.channel().eventLoop();
                if (!channelFuture.isSuccess()) {
                    System.out.println("客户端已启动，与服务端建立连接失败,1s之后尝试重连!");
                    eventLoop.schedule(() -> connect(), 1, TimeUnit.SECONDS);
                }else {
                    System.out.println("客户端已启动成功,开始登录服务端9999");
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws Exception {
        NettyClient c = new NettyClient();
        c.connect();
    }


}
